<?php
class TagMapper extends Mapper{
    const TBL_NAME = 'tag';
    const CONNECTION_TBL_NAME = 'tag_connection';

    public function bindTags($str, $id)
    {
      $taglist = explode(',', strtolower($str));
      foreach ($taglist as $tag) {
        $prepTagList[] = trim($tag); 
      }
      
      $this->createTags($prepTagList);
      $tags = $this->getManyTagsByName($prepTagList);
      $this->addConnections($tags, $id);
    }
    

    public function addConnections(array $tags, $id)
    {
      $str='';
      for ($i=0; $i < count($tags)-1; $i++) { 
        $str.=('(?,?),');
      }
      $str.=('(?,?)');

      $st = $this->db->prepare('INSERT INTO '.self::CONNECTION_TBL_NAME.' (tag_id, bind_to)
                                VALUES '.$str.';');
      for ($i=0; $i < count($tags); $i++) { 
        $tag = $tags[$i];
        $st->bindValue($i*2+1,$tag->get_id(),PDO::PARAM_INT);
        $st->bindValue($i*2+2,$tag->get_id(),PDO::PARAM_INT);
      }
      $st->execute();
      var_dump($st->errorInfo());
    }
    public function createTags(array $tagnames)
    {
      $str='';
      for ($i=0; $i < count($tagnames)-1; $i++) { 
        $str.=('(?),');
      }
      $str.=('(?)');
      $st = $this->db->prepare('INSERT INTO '.self::TBL_NAME.' (name)
                                VALUES '.$str.';');
      for ($i=0; $i < count($tagnames); $i++) { 
        $st->bindValue($i+1, $tagnames[$i]);
      }
      
      $st->execute();
      var_dump($st->errorInfo());
    }

    public function getManyTagsByName($names){
      $str = implode(',', $names);
      $st = $this->db->prepare('SELECT 
                                  id,
                                  name
                                  FROM '.self::TBL_NAME.'
                                  WHERE name IN(?)');
      $st->bindValue(1, $str);
      $st->execute();
      var_dump($st->errorInfo());
      $tagsData = $st->fetchAll(PDO::FETCH_ASSOC);
      $tags = array();
      foreach ($tagsData as $tagData) {
        $tags[] = new TagModel($tagData);
      }
      return $tags;
    }
}
?>